﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Printing;
using FPPrinter.utiles;

namespace FPPrinter.Models.Printers
{
    public class PrinterManager : IPrinterManager
    {
        Dictionary<string, IPrinter> _printers = new Dictionary<string, IPrinter>();

        public void AddPrinter(string printQueueName, bool isDoublesided)
        {
            IPrinter p = new Printer(printQueueName, isDoublesided);
            _printers.Add(printQueueName, p);
        }

        public void StateReport()
        {
            foreach (var p in Printers)
            {
                Console.WriteLine("*");
                p.Echo();
            }
        }


        public void SelectPrinter(string value="")
        {
            
            if (string.IsNullOrEmpty(value))
            {
                var sp = Printers.FirstOrEmpty(x => x.DoubleSided);
                if (sp.IsEmpty) sp = Printers.FirstOrEmpty(x => !x.DoubleSided);
                SelectedPrinter = sp;
            }
            else
            {
                var sp = Printers.FirstOrEmpty(x => x.Name == value);
                SelectedPrinter = sp;
            }
        }

        public void ScanForPrinter()
        {
            var printServer = new LocalPrintServer();
            var printQueues = printServer.GetPrintQueues();
            var pm = this;

            foreach (PrintQueue printQueue in printQueues)
            {
                var capabilities = printQueue.GetPrintCapabilities();
                var isDoublesided = capabilities.DuplexingCapability.Contains(Duplexing.TwoSidedLongEdge);
                pm.AddPrinter(printQueue.Name, isDoublesided);
            }


            pm.SelectPrinter();
        }

        public IEnumerable<IPrinter> Printers
        {
            get => _printers.Values.ToList();
        }

        public IPrinter SelectedPrinter { get; set; }
        // public string PreferedPrinterName { get; set; }
        
    }
}